from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response

from gathering.serializers import *


# 获取活动列表
class ActivityView(GenericAPIView):
    queryset = Gathering.objects.all()
    serializer_class = ActivityModelSerializer

    def get(self, request):
        gathering = self.get_queryset()
        count = gathering.count()
        serializer = self.get_serializer(instance=gathering, many=True)
        return Response({
            'count': count,
            'next': '',  # 分页器-前端缺少反序列化参数
            'previous': '',  # 分页器-前端缺少反序列化参数
            'results': serializer.data
        })


# 活动详情
class ActivityDetailsView(ModelViewSet):
    queryset = Gathering.objects.all()
    serializer_class = ActivityDetails


# 报名活动
class JoinView(APIView):
    def post(self, request, id):
        # 测试登陆
        authorization = request.headers.get('Authorization')
        # # 没登陆则返回
        if not authorization:
            return Response({'message': '用户未登陆', 'success': False})

        # 活动id绑定用户、如果已绑定则取消
        user = request.user
        try:
            gathering = Gathering.objects.get(id=id)
        except Exception as e:
            return Response({'message': '数据库错误', 'success': False})
        # 已报名要取消
        if user in gathering.users.all():
            gathering.users.remove(user)
            return Response({'message': '取消报名成功', 'success': True})
        # 没报名则添加用户
        else:
            gathering.users.add(user)
            return Response({'message': '报名成功', 'success': True})
